import React, { Component } from 'react';
import "../styles/views/Login.scss"

import { user_login } from '../api/index'
import { NavBar, Toast } from 'antd-mobile'

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = { phone: '', pass: '', agree: false }
    }

    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }

    async login() {
        console.log(this.state);

        if (this.state.agree) {
            //发起登陆请求
            let res = await user_login({ phone: this.state.phone, pass: this.state.pass })
            console.log(res);
            if (res.data.code === 200) {
                console.log(1234);
                Toast.show({ content: '登录成功', })
                localStorage.setItem('token', res.data.token)
                localStorage.setItem('id', res.data.userinfo.id)
                this.props.history.push('/index/home')
            } else {
                Toast.show({ content: '登录失败', })
            }
        } else {
            alert('请先勾选用户登陆协议!');
        }
    }
    register() {
        this.props.history.push('/register')
    }
    back() {
        this.props.history.go(-1)
    }
    render() {
        return (
            <div className='login'>
                <NavBar onBack={() => { this.back() }}>登录</NavBar>
                <div className="block">
                    <input name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} type="text" placeholder='输入手机号' />
                </div>
                <div className="block">
                    <input name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} type="text" placeholder='输入密码' />
                </div>
                <div className="block check">
                    <input name='agree' checked={this.state.agree} onChange={(e) => { this.handleChange(e) }} type="checkbox" /> 勾选用户登陆协议.
                </div>
                <div className="block">
                    <input type="button" value="登陆" onClick={() => { this.login() }} />
                </div>
                <div className="block">
                    <input type="button" value="注册" onClick={() => { this.register() }} />
                </div>
            </div>
        );
    }
}

export default Login;